package controllers

import (
	"errors"
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/myblogs/logic"
	"github.com/myblogs/models"
	"github.com/myblogs/pkg/jwt"
	md5p "github.com/myblogs/pkg/md5"
	"github.com/myblogs/pkg/snowflake"
	"go.uber.org/zap"
)

type UserController struct {
	userLogic logic.UserLogic
}

func NewUserController(l logic.UserLogic) *UserController {
	return &UserController{
		userLogic: l,
	}
}
func (u *UserController) LoginHandler(c *gin.Context) {
	var req models.LoginReq
	if err := c.ShouldBindJSON(&req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if ok {
			zap.S().Error("登录参数错误", zap.Error(err))
			ResponseWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))
			return
		}
		Response(c, CodeInvalidParam)
	}
	psBool, err := u.userLogic.Login(c, req)
	if err != nil {
		zap.S().Error("请求错误", zap.Error(err))
		if errors.Is(err, logic.ErrorUserMsg) {
			Response(c, CodeUserExits)
			return
		}
		if errors.Is(err, logic.ErrorEmailMsg) {
			Response(c, CodeEmailExits)
			return
		}
		Response(c, CodeServerBusy)
		return
	}
	if !psBool {
		Response(c, CodePasswordError)
		return
	}
	// 获取用户ID
	userID, err := u.userLogic.GetUserName(c, req.Username)
	if err != nil {
		zap.S().Error("获取用户ID失败", zap.Error(err))
		Response(c, CodeServerBusy)
		return
	}
	// 生成token
	token, err := jwt.GenToken(req.Username, userID)
	if err != nil {
		zap.S().Error("生成token失败", zap.Error(err))
		Response(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, CodeSuccess, map[string]string{
		"token":    token,
		"username": req.Username,
		"userID":   fmt.Sprintf("%d", userID),
	})
}

func (u *UserController) RegisterHandler(c *gin.Context) {
	var req models.User
	if err := c.ShouldBindJSON(&req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		fmt.Println(ok, "ok")
		if ok {
			zap.S().Error("注册参数错误", zap.Error(err))
			ResponseWithMsg(c, CodeInvalidParam, removeTopStruct(errs.Translate(trans)))
			return
		}
		ResponseWithMsg(c, CodeInvalidParam, "请求参数格式错误")
		return

	}
	req.UserID = int(snowflake.NewSnowflake(time.Now(), 1).GetID())
	req.PassWord = md5p.Md5password(req.PassWord)

	user, err := u.userLogic.Register(c, &req)
	if err != nil {
		if errors.Is(err, logic.ErrorUserMsg) {
			Response(c, CodeUserExits)
			return
		}
		if errors.Is(err, logic.ErrorEmailMsg) {
			Response(c, CodeEmailExits)
			return
		}
		Response(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, CodeSuccess, user)
}
